import { PaneModel } from "./PaneModel";
import { modelService } from "@/modules/model/service";
import { ResOwnedDiagram } from "@/modules/model/service/formatRes";
import { PropertyKey } from "@/constants/Enums";

interface TableRow {
  key: string;
  name?: RowType;
  type?: RowType;
  instanceId?: string;
  mergeRows?: boolean;
  children?: TableRow[];
}

interface RowType {
  icon?: string;
  label: string;
  enName?: string;
}

interface Column {
  label: string;
  prop: string;
  resizable: boolean;
  width?: number;
  align: "left" | "center" | "right";
}

export class HyperlinkPaneModel extends PaneModel {
  searchActive = false;
  query = "";
  expandRowKeys = ["general", "existedDiagram", "typeElementExistedDiagram"]; // 当前展开行的key
  selectedKey = "";
  tableData: TableRow[] = [];
  columns: Column[] = [
    {
      label: "models.active",
      prop: "active",
      resizable: true,
      align: "left",
      width: 60
    },
    {
      label: "名称",
      prop: "name",
      resizable: true,
      align: "left"
    },
    {
      label: "类型",
      prop: "type",
      resizable: false,
      align: "left"
    }
  ];

  async loadTableData() {}

  formatData(originalData: { [key: string]: ResOwnedDiagram[] }) {
    for (let key in originalData) {
      const currentItem = this.tableData.filter(item => item.key === key)[0];
      const resData = originalData[key];
      if (!resData) continue;
      const formattedData = resData.map(data => {
        return {
          key: data.instanceId,
          name: {
            label: data.name
          },
          type: {
            label: data.cnType,
            enName: data.enType,
            icon: data.icon
          },
          instanceId: data.instanceId
        };
      });
      currentItem.children = formattedData;
    }
  }
  async getSelectItem() {
    const propertyValue = await modelService
      .getPropertyValueById(this.tabsModel.projectId, this.tabsModel.data!.modelId!, PropertyKey.Element_activeHyperLink)
      .then(data => JSON.parse((data as string) || "{}"));
    if (propertyValue.id) {
      this.selectedKey = propertyValue.id;
    } else {
      this.selectedKey = "defaultNav";
    }
  }

  spreadAll() {
    this.expandRowKeys = ["general", "existedDiagram", "typeElementExistedDiagram"];
  }

  shrinkAll() {
    this.expandRowKeys = [];
  }
  handleSearch() {
    this.searchActive = !this.searchActive;
    if (!this.searchActive) {
      this.query = "";
    }
  }

  /**
   * 如果未加载数据则加载数据
   */
  async loadDataWhenNotLoad(): Promise<void> {
    if (!this.loaded) {
      await this.loadTableData();
    }
  }

  async fresh(): Promise<void> {
    this.loadTableData();
  }

  async clear(): Promise<void> {
    this.tableData = [];
  }
}
